<?php

class ItemController extends Controller {
	
 public function __construct($data) {
        parent::__construct($data);

    }
    
public function index() {
         //ヘッド、メニューなどsmarty設定
		$this->_set_head_footer();		
    $is_showlist=true;
         $this->assign('is_showlist', $is_showlist);
        $this->display('item_index.html');
    	
	 }
	
public function search() {
         //ヘッド、メニューなどsmarty設定
		$this->_set_head_footer();		
    	require_once( '../system/ecjp_m.php' );	 
        
    	$this->assign('goods_status', $ecjp_goods_state);
    	
    	$this->_load_mdao_class("t_m_goods");
    	
    	
       if ( isset( $forms['csv'] ) &&  (  $forms['csv'] == "download" ) ||
			 isset( $forms['hist'] ) &&  (  $forms['hist'] == "2" ) ) {
			$forms =  $_SESSION['MSEARCH']['USER'];
		}else {
			 $forms = $this->g;
			$_SESSION['MSEARCH']['USER'] = $forms;
		}

		//print_r($forms);
        $dao = new t_m_goods;
        $wherearr = array();
        if (isset($forms['free_word']) && (!empty($forms['free_word']) )) {
        	$keyword = '%' .$dao->esc($forms['free_word']). '%';
            $wherearr[] = sprintf("(
                           a.goods_id like    '%s' or
                           a.goods_name like  '%s' or 
	                       a.goods_style like '%s' or 
	                       a.goods_slogan like '%s' or
	                       a.metakeyword  like '%s' )",$keyword, $keyword,  $keyword , $keyword, $keyword);
        }
        
        //状態
        $states = null;
        foreach ($ecjp_goods_state as $k => $v ) {
        	if (isset($forms["goods_statu{$k}"]) && (!empty($forms["goods_statu{$k}"]) )) {
        		$states[] = " a.goods_status = $k ";
        	}
        }
        if ($states) {
        	$wherearr[] = "(".  implode($states, ' or ' ) . ")";
        }
        
        
        
        if (isset($forms['data1']) && (!empty($forms['data1']) )) {
        	$data1=$forms['data1'];
        	$wherearr[] = sprintf("( a.u_time >= '%s')",$data1);
			}
		if (isset($forms['data2']) && (!empty($forms['data2']) )) {
				$data2=$forms['data2'];
				$wherearr[] = sprintf("( a.u_time <= '%s')",$data2);
			}
        
        
		
        if (isset($forms['csv']) && ( $forms['csv'] == "download" )) {
           $g["csv"] = "";
           $tmpfilename = "user" . date("Ymd_His");
           $ua = $_SERVER["HTTP_USER_AGENT"];
           $filename = "$tmpfilename.csv";
           $encoded_filename = urlencode($filename);
           $encoded_filename = str_replace("+", "%20", $encoded_filename);
			header('Content-Type: application/octet-stream');
           if (preg_match("/MSIE/", $ua)) {
           	header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
           }
           else if (preg_match("/Firefox/", $ua)) {
           	header('Content-Disposition: attachment; filename*="utf8\'\'' . $filename . '"');
           }
           else {
           	header('Content-Disposition: attachment; filename="' . $filename . '"');
           }
           
           
          
           
           
           
            $colums = array();
            $col_heads = array(
                'goods_id' => array('コード', 1),
                'goods_name' => array('商品名', 1),
                'goods_unitprice' => array('価格', 1),
                'insideappraise' => array('社内コメント', 1),
                'c_time' => array('登録日時', 1),
                'u_time' => array('更新日時', 1),
            );
            foreach ($col_heads as $k => $v) {
                $colums["name"][] = $k;
                $colums["head"][] = $v[0];
                $colums["type"][$k] = $v[1];
            }
            $data = $dao->search_csv($wherearr);
            //データ整形開始
           
            //データ整形完了
            $dao->output_csv($data, $colums);
            exit;
        }
        
        
         if (isset($forms['page']) && is_numeric($forms['page'])) {
            $dosearch = TRUE;
            $page['current'] = $forms['page'];
        } else {
            $page['current'] = 1;
        }
        $page['item'] = PAGE_MAX;
       // print_r($wherearr);
         $data = $dao->search($wherearr, $page);
         //print_r($data);
        foreach($data as $k=>$v){
        	$imgarr=unserialize($data[$k]['goods_image']);
        	//print_r($imgarr);
        	if($imgarr){
        		$data[$k]['goods_image']=$imgarr[0];
        	}
        	
        	
      		$mode="/\d*_{1}/";
      		preg_match_all($mode, $data[$k]['goods_image'], $formsimgdir);
      		$mode="/[_]/";
      		$imgdirid=preg_replace($mode,'',$formsimgdir[0][0]);
      		$data[$k]['goods_image']=$imgdirid.'/'.$data[$k]['goods_image'];
        	
      		
         }
         
        if(isset($_SERVER['DOCUMENT_ROOT']))
         	$this->assign('path', $_SERVER['DOCUMENT_ROOT']);        
        if (isset($forms))
            $this->assign('forms', $forms);
        if (isset($data))
            $this->assign('data', $data);
        if (isset($page))
            $this->assign('page', $page);
            
        $this->assign('pageing', $this->fetch('page.html'));
        $this->display('item_index.html');
    	
	 }
	 
	 public function insert() {
	 
	 
	 //	echo 'my';
	 	require_once( '../system/ecjp_m.php' );
	 	$this->assign('goods_status', $ecjp_goods_state);
	 	$this->assign('goods_type', $ecjp_goods_type);
	 	$this->assign('goods_mark', $ecjp_goods_mark);
	 	$this->assign('select_month', $ecjp_select_month);
	 	$this->assign('goods_stockstatus', $ecjp_goods_stockstatus);
	 	$this->assign('goods_unit', $ecjp_goods_unit);
	 	$this->assign('rate', RATE);
	 	$phase = 'input';
	 	$show_massg=true;
	 	//ヘッド、メニューなどsmarty設定
		$this->_set_head_footer();

		if ($_SERVER ['REQUEST_METHOD'] == 'GET') {
		    $forms = $this->g;
			$_SESSION['MSEARCH']['USER'] = $forms;		
			$forms[goods_issuedate_year] =  date("Y",time());
			$forms[goods_issuedate_month] = date("m",time());
		}else{
			$forms = $this->p;
			
		}
		
		//$this->_load_mdao_class("t_m_goods");
		//$dao = new t_m_goods;
		//$taxsql = "select flag_value from m_setflag where flag_id =2";
		//$taxres = $dao -> get_rows($taxsql);
		//$tax = $taxres[0][flag_value]/100;
		$this->assign ( 'tax',RATE  );
		
		
		require_once( '../system/Class_ERROR.php' );
		
		if(isset($forms) && $forms['method'] == 'insert'){
			
			$this->_load_php_file("Class_ERROR.php");
			//$forms['goods_issuedate']=$forms['goods_issuedate'].' 00:00:00';
			$forms['goods_image']=serialize($forms ['upload_image_name']);
			//check data
			$err     = new Class_ERROR;
			$chk     = $dao->get_checks();
			foreach ($chk as $kcol => $chkval) {
				$err_mes[$kcol]  = $err->check( $forms[$kcol], $chkval );
			}
			if($err->clear){
				$values = array ();
				$values = $this->set_update_insert_values ( $forms );						    
				$id = $dao->add($values);
				if($id){
					if(!is_dir("images/".$id)){
							mkdir("images/".$id, 0700);
					}
					$images = $forms ['upload_image_name'];
					$newimages = array();
					for($i=0;$i<count($images);$i++){
						$img = $images[$i];
						$typ = substr(strstr($img,"."),1);
						$fileame = $id."_".time().".".$typ;
						$nname = "images/".$id."/".$fileame;
						rename($images[$i], $nname);
						$newimages[$i]= $fileame;
					}
					$values ["goods_image"] = serialize($newimages);
					$dao->edit($id,$values);
					
					$this->insertCategory($forms['category'],$id);
			
					$this->assign('message', '登録が完了しました。');
					$show_massg=false;
				}
			}else{
				$wherecatid = explode("|",$forms['category']);
				
				if(count($wherecatid)>0){
					$wherecatid = implode(",",$wherecatid);
					if(strlen($wherecatid)>0){
						$sql2 = "select * from m_categorygood where category_cd in ($wherecatid)";
						$re2 = $dao -> get_rows($sql2);
						$forms[category_id] = $wherecatid;
						$this->assign ( 'category_data', $re2 );
					}
				}
				
				$forms[tax]=intval($forms[goods_unitprice]*(1+$tax));
			}
		}
		
		$this->assign ( 'forms', $forms );
		$this->assign ( 'err_mes', $err_mes );
		$this->assign ( 'phase', $phase );
		$this->assign('show_massg',$show_massg);
		$this->display('item_regist.html');
	 } 
	 
	 public function insertCategory($cats,$goods_id){
		$arr = explode("|",$cats);
		$this->_load_mdao_class("t_m_goods_category");
		$dao = new t_m_goods_category;
		for($i=0;$i<count($arr);$i++){
			$values['goods_id'] = $goods_id;
			$values['category_id'] = $arr[$i];
			$dao -> add($values);
		}
		
	 }
	 
	 public function deleteCategory($goods_id){
		$this->_load_mdao_class("t_m_goods_category");
		$dao = new t_m_goods_category;
		$dao ->exec_sql("delete from m_goods_category where goods_id =$goods_id");
		
	 }
	 
	/* public function rank(){
	 	 require_once( '../system/ecjp_m.php' );
	 	$this->_load_mdao_class("t_m_goods");
	 	$this->_load_php_file("Class_ERROR.php");
	 	$dao = new t_m_goods;
    	$show_massg=true;
    	//$is_update=false;
    	$g=$this->p;
    	$sql='select * from d_good_rank order by id ';
    	$row=$dao->get_rows($sql);
    	if($g['act']=='save'){
		$err     = new Class_ERROR;
		foreach($g['item'] as $key=>$v ){
				$err_ems['$key']['item']=$err->platform_dependent_characters_filter($v);
				$err_ems['$key']['item_id']=$err->number_check($g['item_id'][$key]);
				$item_text=$v;
				$item_id=$g['item_id'][$key];
				$key_row=$key-1;
				if($row[$key_row]){
					$sql="update d_good_rank set good_id=$item_id,good_name='$item_text',rank=$key where id=".$row[$key_row]['id'];
					if($dao->exec_sql($sql)){
						$this->assign('message', '更新が完了しました。');
							$show_massg=false;
					}
						
				}else{
				 $sql="insert into d_good_rank set good_id=$item_id,good_name='$item_text',rank=$key";
					if($dao->exec_sql($sql)){
							$this->assign('message', '更新が完了しました。');
							$show_massg=false;
						}
					}
				}
    	}
	 	$this->assign('show_massg',$show_massg);
	 	$this->assign('good_date',$row);
	 	$this->display('item_rank.html');
	 }*/
	 
	 
	  public function rank(){
	 	 require_once( '../system/ecjp_m.php' );
	 	$this->_load_mdao_class("t_m_goods");
	 	$this->_load_php_file("Class_ERROR.php");
	 	$this->_set_head_footer();		
	 	
	 	$dao = new t_m_goods;
	 	
    	$show_massg=true;
    	//$is_update=false;
    	$g=$this->p;
    	$sql='select dgr.* ,dg.goods_name from d_good_rank as dgr,d_goods as dg where dgr.good_id=dg.id order by rank ';
    	$row=$dao->get_rows($sql);
		
    	if($g['act']=='save'){
		$err     = new Class_ERROR;
		$sql="DELETE FROM `d_good_rank` ";
				$dao->exec_sql($sql);
		foreach($g['item'] as $key=>$v ){
				$err_ems['$key']['item']=$err->platform_dependent_characters_filter($v);
				$err_ems['$key']['item_id']=$err->number_check($g['item_id'][$key]);
				$item_text=$v;
				$item_id=$g['item_id'][$key];
				if($item_id!=''){
				 $sql="insert into d_good_rank set good_id=$item_id,rank=$key";
					if($dao->exec_sql($sql)){
							$this->assign('message', '更新が完了しました。');
							$show_massg=false;
						}
					}
				}
    	}
		
	 	$this->assign('show_massg',$show_massg);
	 	$this->assign('good_date',$row);
	 	$this->display('item_rank.html');
	 }
	  
   public function update() {
	    require_once( '../system/ecjp_m.php' );
	 	$this->assign('goods_status', $ecjp_goods_state);
	 	$this->assign('goods_type', $ecjp_goods_type);
	 	$this->assign('goods_mark', $ecjp_goods_mark);
	 	$this->assign('goods_stockstatus', $ecjp_goods_stockstatus);
	 	$this->assign('goods_unit', $ecjp_goods_unit);
		$this->assign('select_month', $ecjp_select_month);
		$show_massg=true;
	 	//ヘッド、メニューなどsmarty設定
		$this->_set_head_footer();
		$this->_load_php_file("Class_ERROR.php");
		$g = $this->g;
        $this->_load_mdao_class ( "t_m_goods" );
		// param
		$dao = new t_m_goods;
		//$taxsql = "select flag_value from m_setflag where flag_id =2";
		//$taxres = $dao -> get_rows($taxsql);
		//$tax = $taxres[0][flag_value]/100;
		$this->assign ( 'tax',RATE );
		
		$forms = $this->p;
        if(isset($forms['method']) && $forms['method'] == 'update'){
        	//check data
        	$err     = new Class_ERROR;
        	$chk     = $dao->get_checks();
        	
        	$forms['goods_image']=serialize($forms ['upload_image_name']);
        	foreach ($chk as $kcol => $chkval) {
        		$err_mes[$kcol]  = $err->check( $forms[$kcol], $chkval );
        	}
        	
			$values = array ();
			$values = $this->set_update_insert_values ( $forms );
			
			if( $err->clear ){
				if($dao->edit ( $forms['id'], $values )){
					$this->deleteCategory($forms['id']);
					$this->insertCategory($forms['category'],$forms['id']);
					$this->assign('message', '更新が完了しました。');
				}else{
					$this->assign('message', '更新が失敗しました。');
				}
				$show_massg=false;
				
			}else{
				$wherecatid = explode("|",$forms['category']);
				if(count($wherecatid)>0){
					$wherecatid = implode(",",$wherecatid);
					if(strlen($wherecatid)>0){
						$sql2 = "select * from m_categorygood where category_cd in ($wherecatid)";
						$re2 = $dao -> get_rows($sql2);
						$this->assign ( 'category_id', $wherecatid );
						$this->assign ( 'category_data', $re2 );
					}
				}
				$forms[tax]=intval($forms[goods_unitprice]*(1+$tax));
			}
		}else {
			
			if (isset ( $g ['id'] ) && $g ['id'] != '') {
				if (is_numeric ( $g ['id'] )) {
					$forms = $dao->get ( $g ['id'] );
					$this->_load_mdao_class("t_m_goods_category");
					$cdao = new t_m_goods_category;
					$sql1 = "select category_id from m_goods_category where goods_id =".$g['id'];
					$re1 = $cdao -> get_rows($sql1);
					$catids = array();
					for($i=0;$i<count($re1);$i++){
						$catids[] = $re1[$i]['category_id'];
					}
					if(count($catids)>0){
						$wherecatid = implode(",",$catids);
						$sql2 = "select * from m_categorygood where category_cd in ($wherecatid)";
						$re2 = $cdao -> get_rows($sql2);
						$this->assign ( 'category_data', $re2 );
						$this->assign ( 'category_id', $wherecatid );
					}
					$forms[goods_unitprice]=intval($forms[goods_unitprice]);
					$forms[tax]=intval($forms[goods_unitprice]*(1+$tax));
					$forms[goods_issuedate_year] = date("Y",strtotime($forms[goods_issuedate]));
					$forms[goods_issuedate_month] = date("m",strtotime($forms[goods_issuedate]));
				}
			}
		}
		
		
		//images/11/11_32432.jpg
		
		//images
		$formsimg=unserialize($forms['goods_image']);
		if($forms['upload_image_name']){
			$formsimg=$forms['upload_image_name'];
		}
		//print_r($formsimg);
		if(is_array($formsimg)){
			foreach($formsimg as $key=>$v){
				$mode='/\d*\.{1}/u';
				preg_match_all($mode, $v, $formsimgid);
				
				$mode="/[,\.\:\/]/";
				 $formsimgt[$key]['id']=preg_replace($mode,'',$formsimgid[0][0]);
				 
				 $mode="/\d*_{1}/";
				 preg_match_all($mode, $v, $formsimgdir);
				 $mode="/[_]/";
				 $imgdirid=preg_replace($mode,'',$formsimgdir[0][0]);
				$formsimgt[$key]['imgdir']="images/".$imgdirid.'/'.$v;
				$formsimgt[$key]['img']=$v;
			}
		}
		
		if (isset ( $forms ))	
		$this->assign('formsimg',$formsimgt);	
		$this->assign ( 'err_mes', $err_mes );//print_r($err_mes);
		$this->assign ( 'forms', $forms );
		$this->assign('show_massg',$show_massg);
		$this->display('item_form.html');
	 }
	 
	protected function set_update_insert_values($forms) {
		
			$values = array ();
			$values ["goods_status"] = !empty($forms ['goods_status']) ? $forms ['goods_status'] : '';	
		    $values ["goods_id"] = $forms ['goods_id'];
		    $values ["goods_name"] = $forms ['goods_name'];
		    $values ["goods_type"] = !empty($forms ['goods_type']) ? $forms ['goods_type'] : '';
		    $values ["category_id"] = !empty($forms ['category_id'])?$forms ['category_id']:0;
		    $values ["goods_unitprice"] = $forms ['goods_unitprice'];
		    $values ["goods_stockstatus"] = !empty($forms ['goods_stockstatus']) ? $forms ['goods_stockstatus'] : '';
			$values ["goods_image"] = serialize($forms ['upload_image_name']);
			$_SESSION['goods_image'] = $values ["goods_image"];
		    $values ["goods_issuedate"] = $forms ['goods_issuedate'];
		    $values ["goods_style"] = $forms ['goods_style'];
		    $values ["goods_mark1"] = !empty($forms ['goods_mark1']) ? $forms ['goods_mark1'] : '';
		    $values ["goods_mark2"] = !empty($forms ['goods_mark2']) ? $forms ['goods_mark2'] : '';
		    $values ["goods_unit"] = $forms ['goods_unit'];
		    $values ["goods_slogan"] = $forms ['goods_slogan'];
		    $values ["goods_order"] = $forms ['goods_order'];
		    $values ["metadescription"] = $forms ['metadescription'];
		    $values ["metakeyword"] = $forms ['metakeyword'];
		    $values ["tryURL"] = $forms ['tryURL'];
		    $values ["outsideURL"] = $forms ['outsideURL'];
		    $values ["insideappraise"] = $forms ['insideappraise'];
		    $values ["sellbegin"] = $forms ['sellbegin'];//登???
		    $values ["sellend"] = $forms ['sellend'];//登出??
		    $values ["freespace1"] = $forms ['freespace1'];
		    $values ["freespace2"] = $forms ['freespace2'];
		    $values ["freespace3"] = $forms ['freespace3'];	
		    return $values;
		 
	} 
	
	 public function set(){
	    require_once( '../system/Class_ERROR.php' );
	 	require_once( '../system/ecjp_m.php' );
	 	$this->assign('hg_nu',$ecjp_hg_nu);
	 	$this->assign('hg_na',$ecjp_hg_na);
	 	
	 	$this->assign('lg_nu',$ecjp_lg_nu);
	 	$this->assign('lg_na',$ecjp_lg_na);
	 	
	 	$this->assign('set_order',$ecjp_set_order);
	 	
	 	$this->_load_Class_DAO_OTHER();
	   
		$dao_categorygood = Class_DAO_OTHER::get_categorygood_array_item('商品カテゴリ');
		
		if (isset($dao_categorygood)){
		 	$this->assign('dao_categorygood', $dao_categorygood);
		}
		
	    //ヘッド、メニューなどsmarty設定
		$this->_set_head_footer();
	 	$g = $this->g;
		
	   
        $this->_load_mdao_class ( "t_m_goodsset" );
		$dao = new t_m_goodsset;
		$check = new Class_ERROR();
		
		$user= $g['content'];
		$user1= $g['category'];
		$user2= $g['company'];
		$user3= $g['homepnumber1'];
		
		$mode = $g['mode'];
		
		foreach($dao_categorygood as $k=>$v){
			$cid = $k;
			break;
		}
		
		if(isset($g['mode']) && $g['mode'] == 'select'){
		 	
			$sql = "select * from m_goodsset ";
			if (isset ( $g['category'] ) && $g['category'] != '') {
				if (is_numeric($g['category'])) {
					$sql=$sql." where category=".$g['category'];
					$forms = $dao->get_rows($sql);
					$forms[0]['category']=$g['category'];
				}
			}
		}else if(isset($g['mode']) && $g['mode'] == 'update'){
				$res=$check->exist_check($user);
				$res1=$check->exist_check($user1);
				$res2=$check->exist_check($user2);
				$res3=$check->number_check($user3);
		 
		 	   $forms[0] = $g;
			   if($check->clear){
					$values = $this->update_insert_values ( $forms[0] );
			   }else{
					$this->assign ( 'res', $res );
					$this->assign ( 'res1', $res1 );
					$this->assign ( 'res2', $res2 );
					$this->assign ( 'res3', $res3 );
			   }
		 	  
		 	   if(isset($g['id']) && $g['id'] == ''){	 
		 	   	   if(isset($g['category']) && $g['category'] !='' )
		 	   	   {
		 	   	     $dao->add($values);
		 	   	   } 
		 	   }else {
					$dao->edit ( $g['id'], $values );
		 	   }
		
		 }else{
			
			$sql = "select * from m_goodsset ";
			$sql=$sql." where category=".$cid;
			$forms = $dao->get_rows($sql);
			
		}
		
	    if (isset ( $forms[0] ))		
		$this->assign ( 'forms', $forms[0] );
		
	    if($res=="" || $res1=="" || $res2=="" || $res3==""){
			$this->display('item_setting.html');
	    }else{
	      echo "入力してください";
	    }
		
	 	
	 }
	 
	  
	 	
	 protected function update_insert_values($forms) {
	 	$values = array ();
	 	$values ["content"] = $forms ['content'];
		$values ["homepnumber1"] = $forms ['homepnumber1'];
		$values ["homepnumber2"] = $forms ['homepnumber2'];
		$values ["homepnumber3"] = $forms ['homepnumber3'];
		$values ["category"] = $forms ['category'];
		$values ["hgcd"] = !empty($forms['hgcd']) ? '1':'';
		$values ["hgname"] = !empty($forms['hgname']) ? '1':'';
		$values ["hgimage"] = !empty($forms['hgimage'])?'1':'';
		$values ["hgslogan"] = !empty($forms ['hgslogan'])?'1':'';
		$values ["hgunitprice"] = !empty($forms ['hgunitprice'])?'1':'';
		$values ["hgsale"] = !empty($forms ['hgsale'])?'1':'';
		$values ["listnumber"] = $forms ['listnumber'];
		$values ["lgcd"] = !empty($forms['lgcd']) ? '1':'';
		$values ["lgname"] = !empty($forms['lgname']) ? '1':'';
		$values ["lgimage"] = !empty($forms['lgimage'])?'1':'';
		$values ["lgslogan"] = !empty($forms ['lgslogan'])?'1':'';
		$values ["lgunitprice"] = !empty($forms ['lgunitprice'])?'1':'';
		$values ["lgsale"] = !empty($forms ['lgsale'])?'1':'';
		$values ["orderby"] = !empty($forms ['orderby']) ? $forms ['orderby']:0;
	 	return $values;
	 }
	
	 
	 public function ajaxdeleteimage(){
		$forms = $this->p;
		echo unlink($forms['filename']);
		
	 }
	 
	 
	 public function ajaximage(){
		$error = "";
		$msg = "";
		$uploadfile = "";
		$fileElementName = 'goods_image';
		$uploadfilename = "";
		if(!empty($_FILES[$fileElementName]['error']))
		{
			switch($_FILES[$fileElementName]['error'])
			{

				case '1':
					$error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
					break;
				case '2':
					$error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
					break;
				case '3':
					$error = 'The uploaded file was only partially uploaded';
					break;
				case '4':
					$error = 'No file was uploaded.';
					break;

				case '6':
					$error = 'Missing a temporary folder';
					break;
				case '7':
					$error = 'Failed to write file to disk';
					break;
				case '8':
					$error = 'File upload stopped by extension';
					break;
				case '999':
				default:
					$error = 'No error code avaiable';
			}
		}elseif(empty($_FILES['goods_image']['tmp_name']) || $_FILES['goods_image']['tmp_name'] == 'none')
		{
			$error = 'No file was uploaded..';
		}else 
		{
				$type=strstr($_FILES['goods_image']['name'], '.');
				$id = substr(strstr($_SERVER["QUERY_STRING"],"="),1);
				if(in_array($type, array('.jpg', '.jpeg', '.gif', '.png', '.swf', '.bmp'))) 
				{
					$uploadfilename = $id."_".time().$type;
					$uploadfile = "images/".$id."/".$uploadfilename;
					
					if(!is_dir("images/".$id)){
						mkdir("images/".$id, 0700);
					}
					if (move_uploaded_file($_FILES['goods_image']['tmp_name'], $uploadfile)) {
						$msg = $uploadfile;
					} else {
						$error = "Possible file upload attack!\n";
					}
				}else{
					$error = "The uploaded file was not image!\n";
				}
				
				@unlink($_FILES['goods_image']);		
		}		
		
		echo "{";
		echo				"error: '" . $error . "',\n";
		echo				"msg: '" . $msg . "',\n";
		echo				"path: '" . $uploadfile . "',\n";
		echo				"pathname: '" . $uploadfilename . "',\n";
		echo				"id:'".time(). "'\n";
		echo "}";
	 }
	 

public function refer(){
		require_once( '../system/ecjp_m.php' );
	 	
	 	
	 	$this->assign('goods_mark', $ecjp_goods_mark);
	 	$this->assign('goods_stockstatus', $ecjp_goods_stockstatus);
	 	
		
	 	//ヘッド、メニューなどsmarty設定
		$this->_set_head_footer();
		$this->_load_php_file("Class_ERROR.php");
		$g = $this->g;
        $this->_load_mdao_class ( "t_m_goods" );
		// param
		$dao = new t_m_goods;
		
		$taxsql = "select flag_value from m_setflag where flag_id =2";
		$taxres = $dao -> get_rows($taxsql);
		$tax = $taxres[0][flag_value]/100;
		
		if (isset ( $g ['id'] ) && $g ['id'] != '') {
			if (is_numeric ( $g ['id'] )) {
				$forms = $dao->get ( $g ['id'] );
				$this->_load_mdao_class("t_m_goods_category");
				$cdao = new t_m_goods_category;
				$sql1 = "select category_id from m_goods_category where goods_id =".$g['id'];
				$re1 = $cdao -> get_rows($sql1);
				$catids = array();
				for($i=0;$i<count($re1);$i++){
					$catids[] = $re1[$i]['category_id'];
				}
				if(count($catids)>0){
					$wherecatid = implode(",",$catids);
					$sql2 = "select * from m_categorygood where category_cd in ($wherecatid)";
					$re2 = $cdao -> get_rows($sql2);
					$this->assign ( 'categorys', $re2 );
				}
				$forms[goods_unitprice]=intval($forms[goods_unitprice]);
				$forms[tax]=intval($forms[goods_unitprice]*(1+$tax));
				$forms[goods_issuedate] = date("Y/m",strtotime($forms[goods_issuedate]));
				
			}
		}
		
		
		//images
		$formsimg=unserialize($forms['goods_image']);
		if($forms['upload_image_name']){
			$formsimg=$forms['upload_image_name'];
		}
		
		if(is_array($formsimg)){
			foreach($formsimg as $key=>$v){
				$mode='/\d*\.{1}/u';
				preg_match_all($mode, $v, $formsimgid);
				
				$mode="/[,\.\:\/]/";
				 $formsimgt[$key]['id']=preg_replace($mode,'',$formsimgid[0][0]);
				 
				 $mode="/\d*_{1}/";
				 preg_match_all($mode, $v, $formsimgdir);
				 $mode="/[_]/";
				 $imgdirid=preg_replace($mode,'',$formsimgdir[0][0]);
				$formsimgt[$key]['imgdir']="images/".$imgdirid.'/'.$v;
				$formsimgt[$key]['img']=$v;
			}
		}
		
		if (isset ( $forms ))	
		$this->assign('formsimg',$formsimgt);
		$forms['goods_status'] = $ecjp_goods_state[$forms['goods_status']];
		$forms['goods_type'] = $ecjp_goods_type[$forms['goods_type']];
		$forms['goods_stockstatus'] = $ecjp_goods_stockstatus[$forms['goods_stockstatus']];
		//$forms['goods_issuedate'] = $ecjp_select_month[$forms['goods_issuedate']];
		$forms['goods_unit'] = $ecjp_goods_unit[$forms['goods_unit']];
		$this->assign ( 'forms', $forms );
		$this->display('item_refer.html');
		
	
}




//?出?
public function searchopen() {
	//ヘッド、メニューなどsmarty設定
	$this->_set_head_footer();
	require_once( '../system/ecjp_m.php' );

	$this->assign('goods_status', $ecjp_goods_state);
	 
	$this->_load_mdao_class("t_m_goods");
	 
	 
	if ( isset( $forms['csv'] ) &&  (  $forms['csv'] == "download" ) ||
			isset( $forms['hist'] ) &&  (  $forms['hist'] == "2" ) ) {
		$forms =  $_SESSION['MSEARCH']['USER'];
	}else {
		$forms = $this->g;
		$_SESSION['MSEARCH']['USER'] = $forms;
	}

	//print_r($forms);
	$dao = new t_m_goods;
	$wherearr = array();
	if (isset($forms['free_word']) && (!empty($forms['free_word']) )) {
		$keyword = '%' .$dao->esc($forms['free_word']). '%';
		$wherearr[] = sprintf("(
		                   a.goods_id like    '%s' or
		                   a.goods_name like  '%s' or
	                       a.goods_style like '%s' or
	                       a.goods_slogan like '%s' or
	                       a.metakeyword  like '%s' )", $keyword,$keyword,  $keyword , $keyword, $keyword);
	}

	//状態
	$states = null;
	foreach ($ecjp_goods_state as $k => $v ) {
		if (isset($forms["goods_statu{$k}"]) && (!empty($forms["goods_statu{$k}"]) )) {
			$states[] = " a.goods_status = $k ";
		}
	}
	if ($states) {
		$wherearr[] = "(".  implode($states, ' or ' ) . ")";
	}



	if (isset($forms['data1']) && (!empty($forms['data1']) )) {
		$data1=$forms['data1'];
		$wherearr[] = sprintf("( a.u_time >= '%s')",$data1);
	}
	if (isset($forms['data2']) && (!empty($forms['data2']) )) {
		$data2=$forms['data2'];
		$wherearr[] = sprintf("( a.u_time <= '%s')",$data2);
	}



	if (isset($forms['csv']) && ( $forms['csv'] == "download" )) {
		$g["csv"] = "";
		$tmpfilename = "user" . date("Ymd_His");
		$ua = $_SERVER["HTTP_USER_AGENT"];
		$filename = "$tmpfilename.csv";
		$encoded_filename = urlencode($filename);
		$encoded_filename = str_replace("+", "%20", $encoded_filename);
		header('Content-Type: application/octet-stream');
		if (preg_match("/MSIE/", $ua)) {
			header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
		}
		else if (preg_match("/Firefox/", $ua)) {
			header('Content-Disposition: attachment; filename*="utf8\'\'' . $filename . '"');
		}
		else {
			header('Content-Disposition: attachment; filename="' . $filename . '"');
		}
		 
		 

		 
		 
		 
		$colums = array();
		$col_heads = array(
				'goods_id' => array('コード', 1),
				'goods_name' => array('商品名', 1),
				'goods_unitprice' => array('価格', 1),
				'insideappraise' => array('社内コメント', 1),
				'c_time' => array('登録日時', 1),
				'u_time' => array('更新日時', 1),
		);
		foreach ($col_heads as $k => $v) {
			$colums["name"][] = $k;
			$colums["head"][] = $v[0];
			$colums["type"][$k] = $v[1];
		}
		$data = $dao->search_csv($wherearr);
		//データ整形開始
		 
		//データ整形完了
		$dao->output_csv($data, $colums);
		exit;
	}


	if (isset($forms['page']) && is_numeric($forms['page'])) {
		$dosearch = TRUE;
		$page['current'] = $forms['page'];
	} else {
		$page['current'] = 1;
	}
	$page['item'] = PAGE_MAX;
	// print_r($wherearr);
	$data = $dao->search($wherearr, $page);
	//print_r($data);
	foreach($data as $k=>$v){
		$imgarr=unserialize($data[$k]['goods_image']);
		//print_r($imgarr);
		if($imgarr){
			$data[$k]['goods_image']=$imgarr[0];
		}
		 
		 
		$mode="/\d*_{1}/";
		preg_match_all($mode, $data[$k]['goods_image'], $formsimgdir);
		$mode="/[_]/";
		$imgdirid=preg_replace($mode,'',$formsimgdir[0][0]);
		$data[$k]['goods_image']=$imgdirid.'/'.$data[$k]['goods_image'];
		 

	}
	 
	if(isset($_SERVER['DOCUMENT_ROOT']))
		$this->assign('path', $_SERVER['DOCUMENT_ROOT']);
	if (isset($forms))
		$this->assign('forms', $forms);
	if (isset($data))
		$this->assign('data', $data);
	if (isset($page))
		$this->assign('page', $page);
	$g=$this->g;
	//print_r($g);
	$this->assign('result',$g['result']);
	$this->assign('pageing', $this->fetch('page.html'));
	$this->display('item_alertopen.html');
	 
}
//?出?end
}